package com.lqs.blog.service.Impl;

import com.alibaba.fastjson.JSON;
import com.lqs.blog.pojo.SysUser;
import com.lqs.blog.service.RegisterService;
import com.lqs.blog.service.SysUserService;
import com.lqs.blog.utils.ConstantUtils;
import com.lqs.blog.utils.JWTUtils;
import com.lqs.blog.vo.ErrorCode;
import com.lqs.blog.vo.Result;
import com.lqs.blog.vo.param.RegisterParams;
import io.netty.util.internal.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional//事务回滚
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override

    public Result register(RegisterParams registerParams) {
        String account = registerParams.getAccount();
        String password = registerParams.getPassword();
        String nickName = registerParams.getNickname();
        /*1.判断参数是否为空
         * 2.根据账号和密码去user表中查询 是否存在 若存在 则返回账号已被注册
         * 3.不存在 注册用户
         * 4.生成token
         * 5.存入redis 并返回
         * 6.注意：加上事务 一旦中间过程出现错误 需要回滚
         * */
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password) || StringUtils.isBlank(nickName)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
//        password = DigestUtils.md5Hex(password + ConstantUtils.salt);
        //查询该账号是否存在
        SysUser sysUser = sysUserService.getUserByAccount(account);

        if (sysUser != null) {//表示注册的账户已经存在
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }

        //注册
        sysUser = new SysUser();
        sysUser.setNickname(nickName);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + ConstantUtils.salt));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        this.sysUserService.save(sysUser);
        //生成token
        String token = JWTUtils.createToken(sysUser.getId());
        //存入redis
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
